const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { pool } = require('../config/db');
const auth = require('../middleware/auth'); // 正确导入auth中间件

// 配置文件存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '..', 'uploads', 'leaves');
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成文件名: 时间戳-原始文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024 // 限制文件大小为10MB
  }
});

// 文件上传接口
router.post('/upload', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '未接收到文件'
      });
    }

    // 构建文件访问URL
    const fileUrl = `/uploads/leaves/${req.file.filename}`;

    res.json({
      success: true,
      fileUrl: fileUrl,
      fileName: req.file.originalname,
      message: '文件上传成功'
    });

  } catch (error) {
    console.error('文件上传失败:', error);
    res.status(500).json({
      success: false,
      message: '文件上传失败',
      error: error.message
    });
  }
});

// 提交请假申请 - 使用正确的auth中间件
router.post('/', auth, async (req, res) => {
  try {
    const { type, startDate, endDate, days, reason, attachment } = req.body;
    const userId = req.user?.id;

    // 验证用户ID
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '未登录或登录已过期'
      });
    }

    // 数据验证
    if (!type || !startDate || !endDate || !days || !reason) {
      return res.status(400).json({
        success: false,
        message: '请填写完整的请假信息'
      });
    }

    // 插入请假记录
    const [result] = await pool.query(
      `INSERT INTO leaves (
        studentId,
        type,
        startDate,
        endDate,
        days,
        reason,
        attachment,
        status,
        applyTime
      ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())`,
      [userId, type, startDate, endDate, days, reason, attachment]
    );

    if (result.affectedRows === 1) {
      res.json({
        success: true,
        message: '请假申请提交成功',
        leaveId: result.insertId
      });
    } else {
      throw new Error('插入请假记录失败');
    }

  } catch (error) {
    console.error('提交请假申请失败:', error);
    res.status(500).json({
      success: false,
      message: '提交请假申请失败',
      error: error.message
    });
  }
});

// 获取学生请假记录
router.get('/student', auth, async (req, res) => {
  try {
    const userId = req.user?.id;

    // 验证用户ID
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '未登录或登录已过期'
      });
    }

    // 查询该学生的所有请假记录
    const [leaves] = await pool.query(
      `SELECT l.*, u.name as approverName 
       FROM leaves l
       LEFT JOIN users u ON l.approverId = u.id
       WHERE l.studentId = ?
       ORDER BY l.applyTime DESC`,
      [userId]
    );

    res.json({
      success: true,
      leaves: leaves
    });

  } catch (error) {
    console.error('获取请假记录失败:', error);
    res.status(500).json({
      success: false,
      message: '获取请假记录失败',
      error: error.message
    });
  }
});

// 获取请假详情
router.get('/:id', auth, async (req, res) => {
  try {
    const leaveId = req.params.id;
    const userId = req.user?.id;

    // 验证用户ID
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '未登录或登录已过期'
      });
    }

    // 查询请假详情
    const [leaves] = await pool.query(
      `SELECT l.*, u.name as approverName 
       FROM leaves l
       LEFT JOIN users u ON l.approverId = u.id
       WHERE l.id = ? AND (l.studentId = ? OR u.role IN ('teacher', 'counselor', 'admin'))`,
      [leaveId, userId]
    );

    if (leaves.length === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到请假记录或无权查看'
      });
    }

    // 处理附件信息
    const leave = leaves[0];
    if (leave.attachment) {
      // 确保附件URL是完整的
      if (!leave.attachment.startsWith('http://') && !leave.attachment.startsWith('https://')) {
        // 如果是相对路径，转换为完整URL
        const host = req.get('host');
        const protocol = req.protocol;
        leave.attachmentUrl = `${protocol}://${host}${leave.attachment}`;
      } else {
        leave.attachmentUrl = leave.attachment;
      }
      
      // 获取文件扩展名
      const fileExt = leave.attachment.substring(leave.attachment.lastIndexOf('.') + 1).toLowerCase();
      leave.attachmentType = fileExt;
      
      // 判断是否为图片类型
      leave.isImage = ['jpg', 'jpeg', 'png', 'gif'].includes(fileExt);
    }

    res.json({
      success: true,
      leave: leave
    });

  } catch (error) {
    console.error('获取请假详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取请假详情失败',
      error: error.message
    });
  }
});

module.exports = router;